﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using EvidenceLib.System;
using System.Data;
using EvidenceService.Core;
using EvidenceService.System;
using EvidenceWeb.Models;
using EvidenceWeb.Util;
using NHibernate;
using System.Security.Cryptography;
using System.Text;
using System.Configuration;
using System.Data.SqlClient;

namespace EvidenceWeb.Controllers
{
    public class HomeController : Controller
    {
        private static string LoginViewName = "LoginView";

        //
        // GET: /Home/

        public ActionResult Index()
        {
            if (Session["User"] == null)
            {
                return RedirectToAction("LoginView", "Home");
            }
            else
            {
                return View();
            }
        }

        public ActionResult LoginView()
        {
            return View();
        }
        /// <summary>
        /// 登出注销事件
        /// </summary>
        /// <returns></returns> 
        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();
            HttpContext.Session.Clear();
            return RedirectToAction("LoginView", "Home");
        }

        public ActionResult LoginAction(LogOnModel loginModel)
        {
            bool _ok = String.Equals("a", "A", StringComparison.Ordinal);

            if (ModelState.IsValid)
            {
                using (ISession session = HbmSessionFactory.GetSession())
                {
                    UserService svr = new UserService(session);
                    //User u = svr.LoadByNameAndPwd(user.Name, user.Password);

                    User u = svr.LoadByNameAndPwd(loginModel.UserName, loginModel.Password);

                    if (u != null)
                    {
                        HttpContext.Session.Add("User", u);

                        FormsAuthentication.SetAuthCookie(u.Name, true);
                        Session.Add("User", u);

                        HttpContext.Session["UserId"] = u.Id;
                        HttpContext.Session["UserName"] = u.Name;
                        HttpContext.Session["Password"] = loginModel.Password;
                        HttpContext.Session["OrgName"] = u.Department == null ? "" : u.Department.Name.EndsWith("青羊区分局") ? u.Department.Name : u.Department.Name.Replace("青羊区分局", "");
                        return RedirectToAction("Index", "Home");
                    }
                    else
                    {
                        ModelState.AddModelError("UserName", "警号或密码错误！");
                    }
                }
            }
            else
            {
                return View(LoginViewName);
            }
            return View(LoginViewName);
        }
        /// <summary>
        /// 获取当前用户信息
        /// </summary>
        /// <returns></returns>
        public ActionResult GetLoginUser()
        {
            User user = HttpContext.Session["User"] as User;

            string json = JsonSerializerUtil.EntityToJson(user);

            return Json(new { IsSuccess = true, Data = json });
        }

        public ActionResult CheckPermission()
        {
            User user = HttpContext.Session["User"] as User;

            string roleKey = Request["roleKey"];


            using (ISession session = HbmSessionFactory.GetSession())
            {
                RoleService roleSvr = new RoleService(session);
                bool isPermission = roleSvr.IsPermission(user.Id, roleKey);

                return Json(new { IsPermission = isPermission });
            }

        }

        public ActionResult CheckSession()
        {
            User user = HttpContext.Session["User"] as User;

            bool onLine = false;

            if (user != null)
            {
                onLine = true;
            }
            else
            {
                onLine = false;
            }

            return Json(new { OnLine = onLine });
        }
        /// <summary>
        /// 获取服务端时间
        /// </summary>
        /// <returns></returns>
        public ActionResult GetCurrentTime()
        {
            DateTime time = DateTime.Now;

            return Json(new { IsSuccess = true, Data = time });
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <returns></returns>
        public ActionResult UpdatePassword()
        {
            bool IsSuceed = false;
            string UId = Request["Id"];
            string NewPwd = Request["Password"];
            int userId = 0;
            //ITransaction tx;

            try
            {
                using (ISession session = HbmSessionFactory.GetSession())
                {
                    UserService svr = new UserService(session);



                    //session.Connection

                    //tx = session.BeginTransaction();
                    if (!string.IsNullOrEmpty(UId))
                    {
                        userId = int.Parse(UId);
                    }
                    else
                    {
                        return Json(new { IsSuccess = IsSuceed, Message = "传入后台Id失败！" });
                    }
                    User user = svr.LoadById(userId);

                    MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
                    if (!string.IsNullOrEmpty(NewPwd))
                    {
                        NewPwd = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(NewPwd))).Replace("-", "");
                    }
                    else
                    {
                        return Json(new { IsSuccess = IsSuceed, Message = "传入新密码失败！" });
                    }
                    //string connectionString = ConfigurationManager.AppSettings["connectionString"];
                    //SqlConnection conn = new SqlConnection(connectionString);
                    //conns.Open();
                    IDbCommand cmd = session.Connection.CreateCommand();
                    cmd.CommandText = string.Format("update PoliceMan set Password ='{0}' where id={1}", NewPwd, userId);
                    cmd.CommandType = CommandType.Text;
                    //cmd.ExecuteNonQuery
                    // SqlCommand cmd = new SqlCommand(string.Format("update PoliceMan set Password ='{0}' where id={1}", NewPwd, userId), conn);
                    cmd.ExecuteNonQuery();
                    //conns.Close();
                    //if (user != null)
                    //{
                    //    user.Id = userId;
                    //    user.Password = NewPwd;  
                    //    svr.SaveOrUpdate(user);
                    //    //session.Flush();
                    IsSuceed = true;
                    //    //tx.Commit();
                    //}
                    //else
                    //{
                    //    return Json(new { IsSuccess = IsSuceed, Message = "获取实体对象失败！" });
                    //}
                    return Json(new { IsSuccess = IsSuceed, Message = "密码修改成功，请重新登录！" });
                }
            }
            catch (Exception ex)
            {
                return Json(new { IsSuccess = IsSuceed, Message = "获取实体对象失败！" });
            }
        }

    }
}
